package gpstools.data;

import generated.tcx.TrackpointT;
import generated.tcxext2.ActivityTrackpointExtensionT;
import gpstools.Point;
import gpstools.track.TrackPoint;
import gpstools.track.TrackPoint.Builder;

import java.util.List;

import javax.xml.bind.JAXBElement;

class TcxConverter {
    static TrackPoint pointFromTcx(TrackpointT tcx) {
        /* standard, required */
		if (tcx == null || tcx.getPosition() == null || tcx.getTime() == null) {
            return null;
        }

        final double lon = tcx.getPosition().getLongitudeDegrees();
        final double lat = tcx.getPosition().getLatitudeDegrees();
		final Double ele = tcx.getAltitudeMeters() != null ? tcx
			.getAltitudeMeters().doubleValue() : null;
        final long time = tcx.getTime().toGregorianCalendar().getTimeInMillis();

        Builder builder = TrackPoint.builder(new Point(lat, lon, ele)).time(time);

        /* extensions, optional */
        if (tcx.getHeartRateBpm() != null) {
            builder.heartRate(tcx.getHeartRateBpm().getValue());
        }
        if (tcx.getCadence() != null) {
            builder.cadence(tcx.getCadence());
        }

        if (tcx.getExtensions() != null && tcx.getExtensions().getAny() != null) {
            List<Object> extensions = tcx.getExtensions().getAny();
            for (Object object : extensions) {
                if (object instanceof JAXBElement<?>) {
                    JAXBElement<?> element = (JAXBElement<?>) object;
                    if (element.getValue() instanceof ActivityTrackpointExtensionT) {
                        ActivityTrackpointExtensionT ext = (ActivityTrackpointExtensionT) element.getValue();
                        builder.power(ext.getWatts());
                        builder.speed(ext.getSpeed());
                    }
                }
            }
        }

        TrackPoint point = builder.build();
        
        point.getInfo().setDistanceInMeters(tcx.getDistanceMeters());
        
		return point;
    }
}
